﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;

namespace MPMovieCatalog.Configuration
{
    public class PropertyElement : ConfigurationElement
    {
        public PropertyElement()
            : this("")
        {
        }

        public PropertyElement(string value)
        {
            Value = value;
        }

        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get
            {
                return (string)this["value"];
            }
            set
            {
                this["value"] = value;
            }
        }

        public long ValueAsLong
        {
            get
            {
                try
                {
                    return string.IsNullOrEmpty(Value) ? 0 : long.Parse(Value);
                }
                catch (System.Exception)
                {
                    return 0;
                }
            }
        }

        public bool ValueAsBoolean
        {
            get
            {
                try
                {
                    return string.IsNullOrEmpty(Value) ? false : bool.Parse(Value.ToLower());
                }
                catch (System.Exception)
                {
                    return false;
                }
            }
        }

        public override string ToString()
        {
            return Value;
        }

        protected override bool SerializeToXmlElement(XmlWriter writer, string elementName)
        {
            if (writer != null)
            {
                writer.WriteStartElement("property");
                writer.WriteAttributeString("name", elementName);
                writer.WriteValue(this.Value);
                writer.WriteEndElement();
            }
            return true;
        }
    }
}
